package cn.fintecher.pangolin.service.repair.web;


import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.PhoneNumberData;
import cn.fintecher.pangolin.service.repair.model.PhoneNumberModel;
import cn.fintecher.pangolin.service.repair.respository.PhoneNumberDataRepository;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;


/**
 * Created by huyanmin on 2018/12/26.
 */
@RestController
@RequestMapping("/api/phoneNumberData")
@Api(value = "电话查询", description = "电话查询")
public class PhoneNumberDataController {

    private final Logger log = LoggerFactory.getLogger(PhoneNumberDataController.class);
    @Autowired
    private PhoneNumberDataRepository phoneNumberDataRepository;

    @PostMapping(value = "/insertPhoneNumber")
    @ApiOperation(notes = "新增/更新手机号码", value = "新增/更新手机号码")
    public ResponseEntity<Void> insertPhoneNumber(@RequestParam String csvPath) throws IOException {
        String charset = "GBK";
        FileInputStream fileInputStream = new FileInputStream(csvPath);
        Reader reader = new InputStreamReader(fileInputStream, charset);
        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);

        Map<String, PhoneNumberData> resourceMap = new HashMap<>();
        for (CSVRecord record : records) {
            if (record.getRecordNumber() == 1) {
                continue;
            }
            PhoneNumberData phoneNumberData = new PhoneNumberData();
            phoneNumberData.setPreNumber(record.get(0));
            phoneNumberData.setPhonePeriod(record.get(1));
            phoneNumberData.setPhoneProvince(record.get(2));
            phoneNumberData.setPhoneCity(record.get(3));
            phoneNumberData.setCarrierOperator(record.get(4));
            phoneNumberData.setPostNumber(record.get(5));
            phoneNumberData.setAreaCode(record.get(6));
            phoneNumberData.setAdministrativeAreaCode(record.get(7));
            phoneNumberData.setOperatorTime(ZWDateUtil.getNowDateTime());
            resourceMap.put(phoneNumberData.getPhonePeriod(), phoneNumberData);
        }
        if (resourceMap.size() > 0) {
            Lists.partition(new ArrayList<>(resourceMap.values()), 5000).stream().forEach(phoneNumberData -> phoneNumberDataRepository.saveAll(phoneNumberData));
        }
        return ResponseEntity.ok().build();
    }


    @GetMapping(value = "/searchPhoneNumber")
    @ApiOperation(notes = "查询手机号码归属地", value = "查询手机号码归属地")
    public ResponseEntity<PhoneNumberModel> searchPhoneNumber(@RequestParam String phoneNumber) throws Exception {

        PhoneNumberModel phoneNumberModel = new PhoneNumberModel();
        if(Objects.nonNull(phoneNumber)){
            String number;
            if(phoneNumber.length()>7){
                number = phoneNumber.substring(0,7);
            }else {
                number = phoneNumber;
            }

            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            Iterable<PhoneNumberData> all = phoneNumberDataRepository.search(queryBuilder.must(matchPhraseQuery("phonePeriod", number)));
            all.forEach(phoneNumberData -> {
                phoneNumberModel.setPhoneNumber(phoneNumber);
                phoneNumberModel.getNumberLocations().add(phoneNumberData.getPhoneProvince()+phoneNumberData.getPhoneCity());
                phoneNumberModel.getAdministrativeAreaCodes().add(phoneNumberData.getAreaCode());
                phoneNumberModel.getPostNumbers().add(phoneNumberData.getPostNumber());
                phoneNumberModel.setCardType(phoneNumberData.getCarrierOperator());
            });
        }
        return ResponseEntity.ok(phoneNumberModel);
    }
}
